/**
* @project admin-go-api
* @name authMiddleware
* @descriptions 验证按钮权限
* @author 寒锋
* @date 2023-12-12 14:30:22
 */

package middleware

import (
	"admin-go-api/api/service"
	"admin-go-api/common/response"
	"admin-go-api/constants"
	"github.com/gin-gonic/gin"
	"regexp"
	"strings"
)

func NodeMiddleware() func(c *gin.Context) {
	return func(c *gin.Context) {
		// 获取请求地址
		uri := c.Request.URL
		path := uri.Path
		// 去除左右两则字符
		path = strings.Trim(path, "/")
		// 字符串转数组
		pathArr := strings.Split(path, "/")
		// 匹配是否为数字
		pattern := `/\d+/`
		for index, value := range pathArr {
			// 验证是否为数字，若为路由参数则需要去除
			match, _ := regexp.MatchString(pattern, value)
			if match {
				// 去除为路由参数的数字
				copy(pathArr[index:], pathArr[index+1:])
				pathArr = pathArr[:len(pathArr)-1]
			}
		}
		// 组成新的路由权限标识
		path = strings.Join(pathArr, ".")
		_, err := service.SysMenuService().CheckedNodeByAdmin(c, path)
		if err != nil {
			response.Failed(c, int(constants.ApiCode.DISALLOW), constants.ApiCode.GetMessage(constants.ApiCode.DISALLOW))
			c.Abort()
		}
		c.Next()
	}
}
